//获取歌曲列表
import {Playlist, Song} from "./Constant.ts";
import _ from "lodash";
import "vue-router/dist/vue-router";
import {hook_findSongByPlaylistId} from "./SongHook.ts";
import {defineStore} from "pinia";
import {Howl} from "howler";
import {useLyricsEditPlayerStore} from "./LyricsHook.ts";

export let usePlayerStore = defineStore('player', {
    state: () => ({
        isPlaying: false,
        currentIndex: 0,
        volume: 50,
        currentTime: 0,
        currentLyricIndex: 0,
        duration: 0,
        interval: null,
        showVolume: false,
        showPlayerList: true,
        sound: null,
        playerList: [],
        seekUpdateInterval: null,
        playerListUpdateInterval: null,
        isSeekChange: false,
    }),
    actions: {
        loadSong() {
            console.log("加载")
            console.log(this.currentIndex)
            if (this.sound) {
                this.sound.unload()
            }
            this.clearSeekUpdateInterval()
            this.clearPlayerListUpdateInterval()
            this.sound = new Howl({
                src: this.playerList[this.currentIndex % this.playerList.length]?.url ?? null,
                html5: true,
                autoplay: false,
                volume: this.volume / 100,
                onload: () => {
                    console.log("sound开始加载")
                    this.togglePlayPause()
                },
                onplay: () => {
                    console.log("sound开始播放")
                    this.isPlaying = true
                    this.duration = this.sound?.duration() ?? 0
                    this.currentIndex %= this.playerList.length
                },
                onpause: () => {
                    console.log("sound暂停播放")
                    this.isPlaying = false
                },
                onstop: () => {
                    console.log("sound停止播放")
                    this.isPlaying = false
                    this.currentTime = 0
                },
                onend: () => {
                    console.log("sound完成播放")
                    this.isPlaying = false
                    this.currentTime = 0
                    this.nextSound()
                },
                onseek: () => {
                    console.log("seek发生变化")
                    //监听事件
                    this.currentTime = this.sound?.seek() ?? 0
                },
                onvolume: () => {
                    // this.volume = sound?.volume() ?? 0
                },
                onloaderror: (soundId, error) => {
                    console.error(`Error loading song: ${error}` + soundId)
                },
            })
            this.setSeekUpdateInterval()
            this.setPlayerListUpdateInterval()
        },
        playSound() {
            if (!this.sound) {
                this.loadSong()
            } else {
                this.sound.play()
            }
        },
        togglePlayPause() {
            console.log("播放/暂停"+this.isPlaying)
            if (this.isPlaying) {
                this.pauseSound()
            } else {
                if (this.playerList.length > 0) {
                    this.playSound();
                } else {
                    console.error("歌曲列表为空")
                }
            }
        },
        pauseSound() {
            console.log("暂停")
            this.sound?.pause()
        },
        stopSound() {
            console.log("停止")
            this.sound?.stop()
            this.duration = 0
        },
        afterSound() {
            if (this.playerList?.length != 0) {
                this.stopSound()
                console.log("上一首")
                this.currentIndex = this.currentIndex >= 1 ? this.currentIndex - 1 : this.playerList.length - 1
                this.loadSong()
            } else {
                console.error("歌曲列表为空")
            }
        },
        nextSound() {
            if (this.playerList?.length != 0) {
                this.stopSound();
                console.log("下一首");
                this.currentIndex = (this.currentIndex + 1) % this.playerList.length;
                this.loadSong();
            } else {
                console.error("歌曲列表为空")
            }
        },
        indexSound(index: number) {
            this.stopSound()
            console.log('播放第' + index + '首歌曲')
            this.currentIndex = index
            this.loadSong()
        },
        seekSound(seek) {
            if (this.playerList?.length != 0) {
                console.log("跳过")
                this.sound?.seek(seek)
            } else {
                console.error("歌曲列表为空")
            }
        },
        updatePlayerList() {
            this.playerList = hook_getPlayerList()
            // this.currentTime = 1
            this.currentTime = 0
        },
        removeIndexSong(index) {
            console.log("从播放列表中删除第" + index + "首")
            _.pullAt(this.playerList, index)
            localStorage.setItem("playerList", JSON.stringify(this.playerList))

            //通知storage更新
            this.updatePlayerList()

            //并且播放下一首
            if (index == this.currentIndex) {
                this.indexSound(index)
            } else {
                if (index < this.currentIndex) {
                    //往上移动一位
                    this.currentIndex = this.currentIndex - 1 >= 0 ? this.currentIndex - 1 : 0
                }
            }
        },
        clearPlayerList() {
            this.playerList = []
        },
        setPlayerListUpdateInterval() {
            if (!this.playerListUpdateInterval) {
                this.playerListUpdateInterval = setInterval(() => {
                    let newList = hook_getPlayerList()

                    if (newList.length == 0) {
                        if (usePlayerStore().sound) {
                            console.log("播放列表为0时重置播放器")
                            clearInterval(this.seekUpdateInterval)
                            this.$reset()
                        }
                    }

                    usePlayerStore().playerList = newList;

                }, 500);
            }
        },
        setSeekUpdateInterval(){
            if (!this.seekUpdateInterval) {
                this.seekUpdateInterval = setInterval(() => {
                    if(!this.isSeekChange){
                        this.currentTime = Math.floor(this.sound?.seek()?? 0)
                    }
                    if(useLyricsEditPlayerStore().isPlaying){
                        if(this.isPlaying){
                            this.pauseSound()
                        }
                    }
                }, 1000)
            }
        },
        clearSeekUpdateInterval(){
            if(this.seekUpdateInterval){
                clearInterval(this.seekUpdateInterval)
                this.seekUpdateInterval = null
            }
        },
        clearPlayerListUpdateInterval(){
            if(this.playerListUpdateInterval){
                clearInterval(this.playerListUpdateInterval)
                this.playerListUpdateInterval = null
            }
        }
    }
})


export function hook_getPlayerList() {
    return JSON.parse(localStorage.getItem("playerList")) ?? []
}

//添加歌曲到列表
// @ts-ignore
export function hook_addSongToPlayerList(song: Song, isPlaying?: boolean) {
    console.log("添加")
    let playerList = hook_getPlayerList();
    playerList.splice(0, 0, song);
    let uniq = _.uniqBy(playerList, 'id');
    localStorage.setItem("playerList", JSON.stringify(uniq))

    usePlayerStore().updatePlayerList();

    if (isPlaying) {
        if (usePlayerStore().isPlaying) {
            usePlayerStore().indexSound(0)
        } else {
            usePlayerStore().togglePlayPause()
        }
    }
}

//添加一堆歌曲到PlayerList
// @ts-ignore
export async function hook_addSongsToPlayerList(songs, isPlaying?: boolean = false, isClear?: boolean = false) {
    console.log("添加")
    if (isClear) {
        await usePlayerStore().clearPlayerList()
    }
    await localStorage.setItem("playerList", JSON.stringify(_.uniqBy(_.union(usePlayerStore().playerList, songs), 'id')))

    await usePlayerStore().updatePlayerList();
    if (isPlaying && isClear) {
        if (usePlayerStore().isPlaying) {
            usePlayerStore().indexSound(0)
        } else {
            usePlayerStore().togglePlayPause()
        }
    }



}


//添加歌单到列表
export function hook_addPlaylistToPlayerList(playlist: Playlist) {

    //1.根据歌单获取
    let promiseElement = hook_findSongByPlaylistId(playlist.id)[Symbol.toStringTag];
    console.log(promiseElement);

    // let playList = hook_getPlayList();
    // playList.splice(0, 0, song);
    // let uniq = _.uniqBy(playList, 'id');
    // localStorage.setItem("playList", JSON.stringify(uniq))
}

export function hook_playerPlaying() {

}


//清空播放器列表
export function hook_clearSoundPlayer() {
    localStorage.setItem("playerList", null)
}


export let hook_formatTime = (time: number) => {
    const minutes = Math.floor(time / 60)
    const seconds = Math.floor(time % 60)
    const padZero = (n: number) => (n < 10 ? '0' + n : n)
    return `${padZero(minutes)}:${padZero(seconds)}`
}


